package news.servlet;

import news.dao.UserDao;
import news.pojo.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;

@WebServlet("/login")
public class LoginServlet extends BaseServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        showPage("login");
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String name = request.getParameter("name");
        String pwd = request.getParameter("pwd");
        String code = request.getParameter("code");
        PrintWriter out = response.getWriter();
        // 判断验证码是否正确
        //1.获取session
        HttpSession sess = request.getSession();
        //2.从session拿到验证码字符串
        String trueCode = sess.getAttribute("code").toString();
        //3.判断是否相等
        if (!trueCode.equalsIgnoreCase(code)) { // 一般来说 验证码不区分大小写
            out.println("code not ok!");
            return;
        }
        // 创建数据库操作实例
        UserDao userDao = new UserDao();
        // 通过用户名和密码进行拆线呢
        try {
            User u = userDao.login(name, pwd);
            if (u != null) {
                // 保存登录用户的信息 用于后续检测
                sess.setAttribute("login_user", u);
                // 能否直接跳转 yes
                response.sendRedirect("/news-manage");
            } else {
                out.println("account or password is error");
            }
        } catch (SQLException e) {
            e.printStackTrace();
            out.println("login failed:" + e.getMessage() + e.getSQLState());
        }

    }
}
